package cn.edu.zhku.aspect;

import cn.edu.zhku.aspect.annotation.CheckDataExist;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Aspect
@Component
public class CheckDataExistAspect extends BaseAspect {

    @Pointcut("@annotation(cn.edu.zhku.aspect.annotation.CheckDataExist)")
    public void pointcut() {}

    @AfterReturning(pointcut = "basePointcut() && pointcut()", returning = "result")
    public Object checkDataExist(JoinPoint joinPoint, Object result) {
        JSONObject res = (JSONObject) result;
        CheckDataExist checkDataExist = ((MethodSignature) joinPoint.getSignature())
                .getMethod().getAnnotation(CheckDataExist.class);
        String value = checkDataExist.value();
        Object data = res.get("data");
        if (data == null)
            res.replace("msg", value);
        else if (data instanceof PageInfo) {
            if (((PageInfo<?>) data).getTotal() == 0)
                res.replace("msg", value);
        }
        else if (data instanceof Collection) {
            if (((Collection<?>) data).isEmpty())
                res.replace("msg", value);
        }
        return result;
    }

}
